import { Injectable } from "@angular/core";
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpResponse,
  HttpEvent
} from "@angular/common/http";
import { Observable } from "rxjs";
import { finalize, tap } from "rxjs/operators";
import { StorageService } from './storage.service';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
 
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private storage:StorageService,
              private router: Router,
              private modalService: NzModalService) {}

  private handleError(error:any){
    if(this){
      switch (error.status) {
        case 404:
        // this.router.navigate(['/page404']);
        this.modalService.confirm({
          nzTitle  : '提示',
          nzContent: '<b>登录超时，请重新登录?</b>',
          nzOnOk   : () =>  this.router.navigate(['/login'])
        });
        break;
      }
    }
  }

  intercept(req: HttpRequest<any>,
            next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.storage.getItem('token');
    const authToken = token?token:"";
  
    const authReq = req.clone({
      headers: req.headers.set("token", authToken),
    });
    return next.handle(authReq).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse && event.status === 200) {
            if (event.status === 200) {
              // let result = event.body;
              // if (result.code === 100000) {
              //   this.router.navigate(['/login']);
              //   return false;
              // }
            }
          }
        },
        error => {
          console.log("failed");
          // this.handleError(error)
        }
      ),
      finalize(() => {//请求完成（成功或失败都执行）
      })
    );
  }
}